﻿#ifndef NSSHARE_UTILS_THREAD_POOL_H_
#define NSSHARE_UTILS_THREAD_POOL_H_

#include <queue>
#include "../platform.h"
#include "../base/base_object.h"
#include "../base/atomic.h"
#include "../sys/spin_lock.h"
#include "../sys/thread.h"
#include "job.h"

namespace nsshare
{
namespace utils
{
class Thread;
class ThreadProc;

class ThreadPool : public base::BaseObject
{
public:
    ThreadPool();
    ~ThreadPool();

    bool init(size_t thread_number);
    void fini();

    bool Start();
    void Abort();
    bool Join();

    void QueueJob(JobPtr & ref);

private:
    void DoJobs();

private:
    base::Atomic running_;
    sys::SpinLock job_queue_lock_;
    sys::ThreadProcAdapter<ThreadPool> exec_proc_;
    std::queue<JobPtr> job_queue_;
    sys::Semaphore job_queue_semaphore_;
    std::vector<sys::Thread *> work_threads_;  
};

}
}

#endif